package com.gogowan.agroenterprise;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.ActivationInfo;
import com.gogowan.agroenterprise.model.CodeActivationInfo;
import com.gogowan.agroenterprise.model.CodeActivationResultInfo;
import com.gogowan.agroenterprise.model.MaterialBatch;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.utils.Utils;

/**
 * @author Maniac
 * @功能 激活指定号段的I-OID码
 * @描述 两次交互 1.在拍到起始截至码后执行交互获取批次列表
 * 							2.选择批次列表，激活。
 * @date 2013.7.25 更改码规则
 */
public class ActivateActivityNew extends BaseActivity{
	
	private static int START = 1;	//调用拍码requestCode
	private static int END = 2;
	
	private Button takeStart;        //起始  拍码按钮
	private Button takeEnd;           //截止  拍码按钮
	//private Button getBtn;              //当以输码形式输入时点击获取批次按钮
	private EditText startText;    //起始  I-OID显示
	private EditText endText;		//截止  I-OID显示
	private TextView materialName;
	private LinearLayout layout;
	private Spinner batch;				//选择批次
	
	private Button activateBtn;		//激活按钮
	private Button back;					//返回主页按钮
	
	//private String startCode;
	//private String endCode;
	
	private ProgressDialog progressDialog;
	
	private SharedPreferences sharedPreferences;
	private long enterpriseId = 0;
	private long materialId = 0;
	private long selectedBatch = 0;
	private CodeActivationResultInfo resultInfo;
	private CodeActivationInfo requestBatchsInfo  = new CodeActivationInfo();
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activate);
		
		takeStart = (Button)findViewById(R.id.activate_start_btn);
		takeEnd = (Button)findViewById(R.id.activate_end_btn);
		//getBtn = (Button)findViewById(R.id.activate_get_btn);
		startText = (EditText)findViewById(R.id.activate_start_ed);
		endText = (EditText)findViewById(R.id.activate_end_ed);
		materialName = (TextView)findViewById(R.id.activate_material_name);
		layout = (LinearLayout)findViewById(R.id.activate_layout);
		
		batch = (Spinner)findViewById(R.id.activate_spinner);
		
		activateBtn = (Button)findViewById(R.id.activate_btn);
		back = (Button)findViewById(R.id.activate_cancel_btn); 
		
		batch.setEnabled(false);
		takeEnd.setEnabled(false);
		activateBtn.setEnabled(false);
		sharedPreferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
		enterpriseId = sharedPreferences.getLong("enterpriseid", 0);
		
		takeStart.setOnClickListener(startPaima);
		takeEnd.setOnClickListener(endPaima);
		activateBtn.setOnClickListener(activateBatch);
		back.setOnClickListener(backToIndex);
		//getBtn.setOnClickListener(getBtnCallback);
		
		batch.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				selectedBatch = resultInfo.getMaterialbatchlist()[position].getBatchid();
				materialName.setText(resultInfo.getMaterialbatchlist()[position].getMaterialfullname());
				materialId = resultInfo.getMaterialbatchlist()[position].getMaterialid();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				
			}
		});
	}
	
	/*
	 *  拍起始码按钮事件
	 */
	public Button.OnClickListener startPaima = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					ActivateActivityNew.this);
			builder.setTitle("选择方式");
			builder.setItems(new String[] { "拍产品码", "输产品码" },new AlertDialog.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog,int which) {
					if (which == 0) {
						Intent intent = new Intent(Intents.Scan.ACTION);
						startActivityForResult(intent, START);
					} 
					else if (which == 1) {
						LayoutInflater inflater = LayoutInflater.from(ActivateActivityNew.this);
						View view = inflater.inflate(R.layout.dialog_edit,null);
						final EditText text = (EditText) view.findViewById(R.id.dialog_edittext);
						AlertDialog.Builder builder1 = new AlertDialog.Builder(ActivateActivityNew.this);
						builder1.setTitle("请输入您要拍的码号");
						builder1.setView(view);
						builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								String contents = text.getText().toString().trim();
								if (contents == null || contents.equals("")) {
									Toast.makeText(ActivateActivityNew.this, "码内容不能为空或不符合I-OID规则", Toast.LENGTH_LONG).show();
								} else {
									if (Utils.isNumeric(contents)) {
										startText.setText(contents);
										takeEnd.setEnabled(true);
										takeEnd.setFocusable(true);
									} else {
										Toast.makeText(ActivateActivityNew.this, getString(R.string.code_error), Toast.LENGTH_LONG).show();
									}
								}
							}
						});
						builder1.setNegativeButton("取消", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								
							}
						});
						builder1.create().show();
					}
				}
			}); 
			builder.create().show();
		
		}
	};
	/*
	 *  拍截止码按钮事件
	 */
	public Button.OnClickListener endPaima = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					ActivateActivityNew.this);
			builder.setTitle("选择方式");
			builder.setItems(new String[] { "拍产品码", "输产品码" },new AlertDialog.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog,int which) {
					if (which == 0) {
						Intent intent = new Intent(Intents.Scan.ACTION);
						startActivityForResult(intent, END);
					} 
					else if (which == 1) {
						LayoutInflater inflater = LayoutInflater.from(ActivateActivityNew.this);
						View view = inflater.inflate(R.layout.dialog_edit,null);
						final EditText text = (EditText) view.findViewById(R.id.dialog_edittext);
						AlertDialog.Builder builder1 = new AlertDialog.Builder(ActivateActivityNew.this);
						builder1.setTitle("请输入您要拍的码号");
						builder1.setView(view);
						builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								String contents = text.getText().toString().trim();
								if (contents == null || contents.equals("")) {
									Toast.makeText(ActivateActivityNew.this, "码内容不能为空或不符合I-OID规则", Toast.LENGTH_LONG).show();
								} else {
									
									//endCode = contents;
									progressDialog = ProgressDialog.show(ActivateActivityNew.this, "提示", "正在查询....", true, false);
									CodeActivationInfo caInfo = new CodeActivationInfo();
									caInfo.setStartcode(startText.getText().toString().trim());
									caInfo.setEndcode(contents);
									caInfo.setEnterpriseid(enterpriseId);
									RequestBatchsAsyn requestBatchs = new RequestBatchsAsyn(contents);
									requestBatchs.execute(caInfo);
									
								}
							}
						});
						builder1.setNegativeButton("取消", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								
							}
						});
						builder1.create().show();
					}
				}
			}); 
			builder.create().show();
		
		}
	};
	
	/*
	 *  输码获取
	 */
	/*public Button.OnClickListener getBtnCallback = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			getBtn.setEnabled(false);
			getBtn.setFocusable(false);
			String start = startText.getText().toString().trim();
			String end = endText.getText().toString().trim();
			CodeActivationInfo batchsInfo = new CodeActivationInfo();
			if (start == null || start.equals("")) {
				Toast.makeText(ActivateActivity.this, "起始码不能为空", Toast.LENGTH_LONG).show();
				return;
			} else {
				batchsInfo.setStartcode(start);
			}
			
			if (end == null || end.equals("")) {
				Toast.makeText(ActivateActivity.this, "截止码不能为空", Toast.LENGTH_LONG).show();
				return;
			} else {
				batchsInfo.setEndcode(end);
			}
			
			batchsInfo.setEnterpriseid(enterpriseId);
			
			progressDialog = ProgressDialog.show(ActivateActivity.this, "提示", "正在查询....", true, false);
			RequestBatchsAsyn requestBatchs = new RequestBatchsAsyn();
			requestBatchs.execute(batchsInfo);
		}
	};*/
	/*
	 *  激活按钮事件
	 */
	public Button.OnClickListener activateBatch = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			activateBtn.setEnabled(false);
			activateBtn.setFocusable(false);
			if (selectedBatch == 0) {
				Toast.makeText(ActivateActivityNew.this, getString(R.string.code_error), Toast.LENGTH_LONG).show();
			} else {
				ActivationInfo activationInfo = new ActivationInfo();
				activationInfo.setEnterpriseid(enterpriseId);
				activationInfo.setBatchid(selectedBatch);
				activationInfo.setActivationcode(requestBatchsInfo);
				activationInfo.setMaterialid(materialId);
				progressDialog = ProgressDialog.show(ActivateActivityNew.this, "提示", "正在包装附码....", true, false);
				ActivateAsyn activateAsyn = new ActivateAsyn();
				activateAsyn.execute(activationInfo);
			}
		}
	};
	/*
	 *  返回主页按钮事件
	 */
	public Button.OnClickListener backToIndex = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			AlertDialog alert = new AlertDialog.Builder(ActivateActivityNew.this)
			.setTitle(getString(R.string.tip_back)).setCancelable(false)
			.setMessage(getString(R.string.tip_back_description))
					.setNegativeButton("否", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// do nothing
						}
					})
					.setPositiveButton("是", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// 结束应用程序
							ActivateActivityNew.this.finish();
						}
					}).create();
			alert.show();
		}
	};

	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			AlertDialog alert = new AlertDialog.Builder(ActivateActivityNew.this)
			.setTitle(getString(R.string.tip_back)).setCancelable(false)
			.setMessage(getString(R.string.tip_back_description))
					.setNegativeButton("否", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// do nothing
						}
					})
					.setPositiveButton("是", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// 结束应用程序
							ActivateActivityNew.this.finish();
						}
					}).create();
			alert.show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 拍码返回处理
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {
			if (requestCode == START) {
				
				String contents = data.getStringExtra("SCAN_RESULT").trim();
				String [] ss = contents.split("=");
				contents = ss[ss.length-1];
				
				startText.setText(contents);
				takeEnd.setEnabled(true);
					
				
			} else if (requestCode == END) {
				
				String contents = data.getStringExtra("SCAN_RESULT").trim();
				String [] ss = contents.split("=");
				contents = ss[ss.length-1];
				
				
				//endCode = contents;
				progressDialog = ProgressDialog.show(ActivateActivityNew.this, "提示", "正在查询....", true, false);
				CodeActivationInfo caInfo = new CodeActivationInfo();
				caInfo.setStartcode(startText.getText().toString().trim());
				caInfo.setEndcode(contents);
				caInfo.setEnterpriseid(enterpriseId);
					
				RequestBatchsAsyn requestBatchs = new RequestBatchsAsyn(contents);
				requestBatchs.execute(caInfo);
				
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	/**
	 * @author Maniac
	 * @描述 根据首尾I-OID码请求批次列表
	 */
	private class RequestBatchsAsyn extends MyAsyncTask{
		CodeActivationInfo request;
		private String endcode;
		
		public RequestBatchsAsyn(String contents) {
			this.endcode = contents;
		}
		
		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(ActivateActivityNew.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(ActivateActivityNew.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					resultInfo = (CodeActivationResultInfo)Utils.fromJSON(string, CodeActivationResultInfo.class);
					
					if (resultInfo.getResult() == 5010) {
						endText.setText(endcode);
						final MaterialBatch[] batchs = resultInfo.getMaterialbatchlist();
						if (batchs == null || batchs.length == 0) {
							Toast.makeText(ActivateActivityNew.this, "批次列表空", Toast.LENGTH_LONG).show();
						} else {
							
							batch.setEnabled(true);
							activateBtn.setEnabled(true);
							layout.setVisibility(View.VISIBLE);
							requestBatchsInfo = request; //只有传进请求方法的 并且请求成功的才可以放入激活对象中去
							
							String [] m = new String[batchs.length];
							for (int i = 0; i < batchs.length; i++) {
								m[i] = batchs[i].getBatchcode();
							}
							ArrayAdapter<String> adapter = new ArrayAdapter<String>(ActivateActivityNew.this,android.R.layout.simple_spinner_item,m);
							//设置下拉列表的风格
							 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
							 //将adapter 添加到spinner中
							 batch.setAdapter(adapter);
						}
						
						
					} else {
						Toast.makeText(ActivateActivityNew.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
					}
				}
			}
			//getBtn.setEnabled(true);
			//getBtn.setFocusable(true);
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			request = (CodeActivationInfo)params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(5000, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
		
	}

	/**
	 * @author Maniac
	 * @功能 激活选中的批次号
	 */
	private class ActivateAsyn extends MyAsyncTask{

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				startText.setText("");
				endText.setText("");
				//startCode = null;
				//endCode = null;
				takeEnd.setEnabled(false);
				takeEnd.setFocusable(false);
				batch.setEnabled(false);
				activateBtn.setEnabled(false);
				Toast.makeText(ActivateActivityNew.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					startText.setText("");
					endText.setText("");
					//startCode = null;
					//endCode = null;
					takeEnd.setEnabled(false);
					takeEnd.setFocusable(false);
					batch.setEnabled(false);
					activateBtn.setEnabled(false);
					Toast.makeText(ActivateActivityNew.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					ResultInfo resultInfo = (ResultInfo)Utils.fromJSON(string, ResultInfo.class);
					if (resultInfo.getResult() == 5110) {
						Toast.makeText(ActivateActivityNew.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
						ActivateActivityNew.this.finish();
					} else {
						startText.setText("");
						endText.setText("");
						//startCode = null;
						//endCode = null;
						takeEnd.setEnabled(false);
						takeEnd.setFocusable(false);
						batch.setEnabled(false);
						activateBtn.setEnabled(false);
						Toast.makeText(ActivateActivityNew.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			ActivationInfo request = (ActivationInfo)params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(5100, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}
}
